﻿define(['app', '/Modules/TinyMce/Scripts/tiny_mce.js'], function (app) {
    /**
     * Binds a TinyMCE widget to <textarea> elements.
     */
    app.lazy.provide.value('uiTinymceConfig', {});
    app.lazy.directive('uiTinymce', ["uiTinymceConfig", function (uiTinymceConfig) {
          uiTinymceConfig = uiTinymceConfig || {};
          var generatedIds = 0;
          return {
              require: 'ngModel',
              link: function (scope, elm, attrs, ngModel) {
                  var expression, options, tinyInstance,
                    updateView = function () {
                        ngModel.$setViewValue(elm.val());
                        if (!scope.$$phase) {
                            scope.$apply();
                        }
                    };
                  // generate an ID if not present
                  if (!attrs.id) {
                      var instanceId = 'uiTinymce' + generatedIds++;
                      attrs.$set('id', instanceId);
                  }

                  if (attrs.uiTinymce) {
                      expression = scope.$eval(attrs.uiTinymce);
                  } else {
                      expression = {};
                  }

                  var mediaPlugins = ",|";

                  options = {
                      // Update model when calling setContent (such as from the source editor popup)
                      setup: function (ed) {
                          var args;
                          //ed.on('init', function (args) {
                          //    ngModel.$render();
                          //});
                          //// Update model on button click
                          //ed.on('ExecCommand', function (e) {
                          //    ed.save();
                          //    updateView();
                          //});
                          //// Update model on keypress
                          //ed.on('KeyUp', function (e) {
                          //    ed.save();
                          //    updateView();
                          //});
                          //// Update model on change, i.e. copy/pasted text, plugins altering content
                          //ed.on('SetContent', function (e) {
                          //    if (!e.initial) {
                          //        ed.save();
                          //        updateView();
                          //    }
                          //});

                          ed.onInit.add(function (args) {
                              ngModel.$render();
                          });
                          // Update model on button click
                          ed.onExecCommand.add(function (e) {
                              ed.save();
                              updateView();
                          });
                          // Update model on keypress
                          ed.onKeyUp.add(function (e) {
                              ed.save();
                              updateView();
                          });
                          // Update model on change, i.e. copy/pasted text, plugins altering content
                          ed.onSetContent.add(function (e) {
                              if (!e.initial) {
                                  ed.save();
                                  updateView();
                              }
                          });
                          if (expression.setup) {
                              scope.$eval(expression.setup);
                              delete expression.setup;
                          }
                      },
                      theme: "advanced",
                      schema: "html5",
                      mode: 'exact',
                      elements: attrs.id,
                      editor_selector: "tinymce",
                      plugins: "fullscreen,autoresize,searchreplace," + mediaPlugins.substr(2),
                      theme_advanced_toolbar_location: "top",
                      theme_advanced_toolbar_align: "left",
                      theme_advanced_buttons1: "search,replace,|,cut,copy,paste,|,undo,redo" + mediaPlugins + ",|,link,unlink,charmap,emoticon,codeblock,|,bold,italic,|,numlist,bullist,formatselect,|,code,fullscreen,",
                      theme_advanced_buttons2: "",
                      theme_advanced_buttons3: "",
                      convert_urls: false,
                      valid_elements: "*[*]",
                      // shouldn't be needed due to the valid_elements setting, but TinyMCE would strip script.src without it.
                      extended_valid_elements: "script[type|defer|src|language]"
                  };
                  // extend options with initial uiTinymceConfig and options from directive attribute value
                  angular.extend(options, uiTinymceConfig, expression);
                  setTimeout(function () {
                      tinymce.init(options);
                  }, 100);


                  ngModel.$render = function () {
                      if (!tinyInstance) {
                          tinyInstance = tinymce.get(attrs.id);
                      }
                      if (tinyInstance) {
                          tinyInstance.setContent(ngModel.$viewValue || '');
                      }
                  };
              }
          };
    }]);
});